package example.other;

import android.content.Context;
import android.os.Environment;
import android.util.Log;


import com.example.baselibrary.R;

import net.tsz.afinal.FinalDb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 初始化数据库
 * @author Soomi
 *
 */
public class DatabaseUtil {
	 private static final String TAG="DatabaseUtil";
	private static FinalDb db;
	 private static final int BUFFER_SIZE =400000;
	 public static final String DB_NAME ="clientdb.db"; //保存的数据库文件名
	 public static final String PACKAGE_NAME ="com.example.qingyun.basefunction";  // 要相同
	 public static final String DB_PATH ="/data"
	            + Environment.getDataDirectory().getAbsolutePath() +"/"
	            + PACKAGE_NAME; //在手机里存放数据库的位置
	 public static final String dbfile = DB_PATH+"/"+DB_NAME;
	 /**创建或导入数据库
	  * 
	  * @param context
	  */
	 public static void createDatabase(Context context) {
	        try{
	        	Log.i("myinfo", "操作数据库");
	            if(!(new File(dbfile).exists())) {//判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
	                InputStream is =context.getResources().openRawResource(
	                        R.raw.clientdb);//欲导入的数据库
	                Log.i("myInfo", "导入数据库");
	                FileOutputStream fos =new FileOutputStream(dbfile);
	                byte[] buffer =new byte[BUFFER_SIZE];
	                int count =0;
	                while((count = is.read(buffer)) >0) {
	                    fos.write(buffer,0, count);
	                }
	                fos.close();
	                is.close();
	            }
				else {
					//若数据库改动了,安装后,先删除本地的再重新写入即可.
					// 先更新数据，
					Log.i(TAG,"数据库改动,重新安装");
					File file=new File(dbfile);
					file.delete();
					InputStream is =context.getResources().openRawResource(
							R.raw.clientdb);//欲导入的数据库
					Log.i("myInfo", "导入数据库");
					FileOutputStream fos =new FileOutputStream(dbfile);
					byte[] buffer =new byte[BUFFER_SIZE];
					int count =0;
					while((count = is.read(buffer)) >0) {
						fos.write(buffer,0, count);
					}
					fos.close();
					is.close();
				}

				if(db==null)    db = FinalDb.create(context, dbfile, true, 300800, null);
	        
	        }catch(FileNotFoundException e) {
	            Log.e("Database","File not found");
	            e.printStackTrace();
	        }catch(IOException e) {
	            Log.e("Database","IO exception");
	            e.printStackTrace();
	        }
	       
	    }
	 /**
	  * 获取FinalDb
	  * @param context
	  * @return
	  */
	 public static FinalDb getDatabase(Context context){
		 if(db==null)
			  return FinalDb.create(context, dbfile, true, 300800, null);
		 else 
			 return db;
	 }
	public synchronized static FinalDb getDb(){
		return db;
	}


	/***
	 * 可以实现 自动更新数据库 ;
	 */




//	public static void updateLesson(BaseLesson customLesson) {
//		db.update(customLesson, "lesson_name = "+"'"+customLesson.getLesson_name()+"'"
//				+ " and "+ "type = "+"'"+customLesson.getType()+"'"
//				+ " and " + "teacher_id="+"'"+ customLesson.getTeacher_id() + "'");
////		deleteLesson(customLesson);
////		db.save(customLesson);
//	}
//	//
//
//	public static void saveCustomLesson(CustomLesson customLesson) {
//				deleteLesson(customLesson);
//		db.save(customLesson);
//	}
//
//	public static void saveSysLesson(SystemLesson customLesson) {
//		deleteSysetemLesson(customLesson);
//		db.save(customLesson);
//	}
//	public static void deleteLesson(BaseLesson i) {
//		db.deleteByWhere(CustomLesson.class, "lesson_name = "+"'"+i.getLesson_name()+"'"
//				+ " and " + "type = "+"'"+i.getType()+"'"
//				+ " and " + "teacher_id = "+"'"+ i.getTeacher_id() + "'");
//	}
//
//	public static void deleteSysetemLesson(BaseLesson i) {
//		db.deleteByWhere(SystemLesson.class, "lesson_name = "+"'"+i.getLesson_name()+"'"
//				+ " and " + "type = "+"'"+i.getType()+"'"
//				+ " and " + "teacher_id = "+"'"+ i.getTeacher_id() + "'");
//	}
//	public static void deletePurchasedLesson(PurchasedLesson i) {
//		db.deleteByWhere(PurchasedLesson.class, "lesson_name = "+"'"+i.getLesson_name()+"'"
//				+ " and " + "type = "+"'"+i.getType()+"'"
//				+ " and " + "teacher_id = "+"'"+ i.getTeacher_id() + "'");
//	}
//
//	 /**从部分的CustomLesson 得到完整的Lesson**/
//	 public static CustomLesson getFullCustomLessonFromPart(BaseLesson lesson){
//	   List<CustomLesson> list = DatabaseUtil.getDb().findAllByWhere(
//				 CustomLesson.class,"teacher_id="+lesson.getTeacher_id()+" and "+
//				 "lesson_name=" + "'" +
//						lesson.getLesson_name() + "' and "
//						 + "type=" + "'" + lesson.getType() + "'");
//		 if (list!=null){
//			 if (list.size()>0){
//				 return list.get(0);
//			 }
//		 }
//        return null;
//	 }
//	/**从部分的CustomLesson 得到完整的Lesson**/
//	public static SystemLesson getFullSystemLessonFromPart(BaseLesson lesson){
//		List<SystemLesson> list = DatabaseUtil.getDb().
//				findAllByWhere(
//				SystemLesson.class,"teacher_id="+lesson.getTeacher_id()+" and "+
//						"lesson_name=" + "'" +
//						lesson.getLesson_name() + "' and "
//						+ "type=" + "'" + lesson.getType() + "'");
//		if (list!=null){
//			if (list.size()>0){
//				return list.get(0);
//			}
//		}
//		return null;
//	}
//
//
//	 public static CustomLesson getCustomLessonSFromLessonId(int lessonId){
//		 List<CustomLesson> list = DatabaseUtil.getDb().findAllByWhere(
//				 CustomLesson.class,"lesson_id="+lessonId);
//		 if (list!=null){
//			 if (list.size()>0){
//				 return list.get(0);
//			 }
//		 }
//		 return null;
//
//
//
//	 }
//
//
//
//	/**从部分的CustomLesson 得到完整的Lesson**/
//	public static CheckingLesson getFullCheckingLessonFromPart(BaseLesson lesson){
//		List<CheckingLesson> list = DatabaseUtil.getDb().findAllByWhere(
//				CheckingLesson.class,"teacher_id="+lesson.getTeacher_id()+" and "+
//						"lesson_name=" + "'" +
//						lesson.getLesson_name() + "' and "
//						+ "type=" + "'" + lesson.getType() + "'");
//		if (list!=null){
//			if (list.size()>0){
//				return list.get(0);
//			}
//		}
//		return null;
//	}
}
